package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysRole.SysRoleService;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(String account, String password,
                        HttpSession session, Model model) throws Exception {
            SysUser user=sysUserService.login(account,password);
            if(null!=user){
                session.setAttribute(Constants.USER_SESSION,user);
                return "frame";
            }else{
                /*model.addAttribute("error","用户名或密码错误");
                return "login";*/
                throw  new RuntimeException("用户名或密码错误");
            }
    }
    @RequestMapping("/sys/list")
    public String list(String queryRealName,Integer queryRoleId,Integer pageIndex,Model model) throws Exception {
        int pageSize=Constants.pageSize;
        if(null==pageIndex){
            pageIndex=1;
        }
        List<SysUser> list=sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
        Integer count=sysUserService.getUserCount(queryRealName,queryRoleId);
        PageSupport pageSupport=new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setCurrentPageNo(pageIndex);
        pageSupport.setTotalCount(count);
        List<SysRole> roleList=sysRoleService.getRoleList();
        //传到查询页面的数据
        model.addAttribute("roleList",roleList);
        model.addAttribute("userList",list);
        model.addAttribute("page",pageSupport);
        //条件回显
        model.addAttribute("queryRealName",queryRealName);
        model.addAttribute("queryRoleId",queryRoleId);
        return "/sysUser/list";
    }
    @RequestMapping("/sys/toAdd")
    public String toAdd(){
        return "/sysUser/add";
    }
    @PostMapping("/sys/add")
    public String add(SysUser user, HttpSession session,
                      MultipartFile[] idPic,Model model) throws Exception {
        //判断是否有文件按
        //上传的路径
        //判断文件大小合适，文件的格式（获取文件后缀）合适
        //上传multipartfile.transferTo()
        //获取上传的文件路径+名称放到数据库中
        String idPicPath="";
        String workPicPath="";
        for (int i = 0; i <idPic.length ; i++) {
            MultipartFile pic=idPic[i];
            if(null!=pic){
                //定义文件上传的路径
                String path=session.getServletContext().getRealPath("/statics"+ File.separator+"upload/");
                int size=500000;
                String oldFileName=pic.getOriginalFilename();
                String suffix= FilenameUtils.getExtension(oldFileName);
                if(pic.getSize()>size){
                    if(i==0){
                        model.addAttribute("uploadFileError","文件大小不能超过500KB");
                    }else{
                        model.addAttribute("uploadWpError","文件大小不能超过500KB");
                    }
                    return "/sysUser/add";
                }else if(suffix.equalsIgnoreCase("jpg")||
                        suffix.equalsIgnoreCase("png")||
                        suffix.equalsIgnoreCase("jpeg")||
                        suffix.equalsIgnoreCase("pneg")){
                    //对文件进行重命名
                    String newFileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"."+suffix;
                    File newFile=new File(path,newFileName);
                    if(!newFile.exists()){
                        newFile.mkdirs();
                    }
                    try{
                        //文件上传
                        pic.transferTo(newFile);
                        if(i==0){
                            idPicPath=newFile.getPath();
                        }else{
                            workPicPath=newFile.getPath();
                        }
                    }catch (Exception e){
                        if(i==0){
                            model.addAttribute("uploadFileError","上传失败");
                        }else{
                            model.addAttribute("uploadWpError","上传失败");
                        }
                        return "/sysUser/add";
                    }
                }else{
                    if(i==0){
                        model.addAttribute("uploadFileError","文件格式不正确");
                    }else{
                        model.addAttribute("uploadWpError","文件格式不正确");
                    }
                    return "/sysUser/add";
                }
            }
        }
        user.setWorkPicPath(workPicPath);
        user.setIdPicPath(idPicPath);
        user.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreatedTime(new Date());
        boolean flag=sysUserService.add(user);
        if(flag){
            return "redirect:/user/list";
        }else{
            return "/sysUser/add";
        }
    }
    @GetMapping("/view/{userId}")
    @ResponseBody
    public SysUser view(@PathVariable Integer userId,Model model) throws Exception {
        SysUser user= null;
        user = sysUserService.getUserById(userId);
        return user;
    }
    @GetMapping("/toUpdate/{userId}")
    public String toUpdate(@PathVariable Integer userId,Model model) throws Exception {
        model.addAttribute("sysUser",sysUserService.getUserById(userId));
        return "/sysUser/update";
    }
    @PostMapping("/update")
    public String update(SysUser user,HttpSession session) throws Exception {
        user.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setUpdatedTime(new Date());
        boolean flag=sysUserService.update(user);
        if(flag){
            return "redirect:/user/list";
        }else{
            return "/sysUser/update";
        }
    }
    @RequestMapping("/addFrm")
    public String toAddFrm(@ModelAttribute("sysUser") SysUser sysUser){
        return "/sysUser/addFrm";
    }
    @PostMapping("/addFrm")
    public String addFrm(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session) throws Exception {
        if(bindingResult.hasErrors()){
            return "/sysUser/addFrm";
        }
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        sysUser.setCreatedTime(new Date());
        boolean flag=sysUserService.add(sysUser);
        if(flag){
            return "redirect:/user/list";
        }else{
            return "/sysUser/addFrm";
        }
    }
    @GetMapping("/userExist")
    @ResponseBody
    public Object userExist(String account) throws Exception {
        String json="";
        Map<String,Object> map=new HashMap<>();
        SysUser user=sysUserService.getByAccount(account);
        if(null!=user){
            map.put("exist",1);
        }else{
            map.put("exist",0);
        }
        json= JSON.toJSONString(map);
        return json;
    }
    @GetMapping("/del")
    @ResponseBody
    public Object del(Integer uid){
        Map<String,String> map=new HashMap<>();
        if(null==uid){
            map.put("delResult","notexist");
        }
        try {
           boolean flag=sysUserService.deleteById(uid);
           if(flag){
               map.put("delResult","true");
           }else{
               map.put("delResult","false");
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
